package com.market.dao.jpa;

import java.util.Date;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.market.dao.PromotionDao;
import com.market.domain.Location;
import com.market.domain.Promotion;
import com.market.domain.Role;

@Repository("promotionDao")
public class PromotionDaoJpa extends GenericDaoJpa<Promotion, Long> implements
		PromotionDao {

	public PromotionDaoJpa() {
		super(Promotion.class);
	}

	public void remove(Promotion promotion) {
		if (this.findById(promotion.getId()) == null) {
			log.debug(this.getClass() + " Promotion with id "
					+ promotion.getId() + " not found, can not be deleted");
		} else {
			log.debug(this.getClass() + " Promotion with id "
					+ promotion.getId() + " found, will be deleted");
			super.removeById(promotion.getId());
		}

	}

	public List<Location> findLocations(Promotion promotion) {
		String sql = "select location.* from location, promotion_location where location.id=promotion_location.locations_id "
				+ " and promotion_location.promotion_id = " + promotion.getId();
		Query query = this.em.createNativeQuery(sql, Location.class);
		List<Location> locations = query.getResultList();
		return locations;
	}

	public List<Promotion> findValidPromotions(Date date, Long locationId) {
		String sql = "select promotion.* from promotion,promotion_location  where promotion.id=promotion_location.promotion_id and "
				 + " promotion_location.locations_id = " + locationId + " and ('" +  new java.sql.Date(date.getTime()) + "' between startdate and enddate)";
		Query query = this.em.createNativeQuery(sql, Promotion.class);
		List<Promotion> promotions = query.getResultList();
		return promotions;
	}

}
